package io;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
import java.util.Vector;

import datastructures.Interaction;

/*
 * Reads a flat file with no header. Starting with first entry, all lines are pairs like this:
 * r	rs52452	d	rs54364
 * ...
 */
public class SxpcFileReader {
	
	public Interaction[] readProcessedHitsFile(String hitsfileName) throws IOException {
		
		BufferedReader hitsfile = new BufferedReader(new FileReader(hitsfileName));
		hitsfile.readLine(); //waste the header
		
		//store contents in a vector
		Vector<Interaction> hitsfileContents = new Vector<Interaction>();
		String entry;
		while( (entry=hitsfile.readLine()) != null) {
			hitsfileContents.add(new Interaction(entry));
		}
		
		//transfer to an array
		Interaction[] interactionList = new Interaction [hitsfileContents.size()];
		for(int i=0; i<hitsfileContents.size(); i++) {
			interactionList[i] = hitsfileContents.elementAt(i);
		}
		hitsfileContents = null;
		
		return interactionList;
	}
	
	public Integer[] readHitsIndexFile(String hitsIndexFileName) throws IOException {
		Vector<Integer> hitsIndices = new Vector<Integer>(); 
		try{
			BufferedReader b = new BufferedReader(new FileReader(hitsIndexFileName));
			
			String line = null; 
			while( (line = b.readLine()) != null ) 
				hitsIndices.add(Integer.parseInt(line));
			
			} catch (IOException e ) {
				e.printStackTrace();
				System.exit(1);
			}
			
		Integer[] hitsIndexArray = new Integer[hitsIndices.size()];
		hitsIndices.toArray(hitsIndexArray);
		return hitsIndexArray;
	}
	
	public Vector<String[]> readUnprocessedHitsFile(String hitsfileName) throws IOException {
		Vector<String[]> variables = new Vector<String[]>();
		
		try{
			BufferedReader b = new BufferedReader(new FileReader(hitsfileName));
			
			String line = null; 
			while( (line = b.readLine()) != null ) {
				StringTokenizer strTok = new StringTokenizer(line,"\t");
				if(strTok.countTokens() == 0 || strTok.countTokens() %2 != 0)
					break;
				
				boolean alreadyHasPvals = strTok.countTokens() % 2 == 0 ? false : true;
				int leaveBehindTokens = 0;
				if ( alreadyHasPvals ) 
					leaveBehindTokens = 1;
				
				String[] interaction = new String[strTok.countTokens() - leaveBehindTokens];
				for ( int entry=0; strTok.countTokens() > leaveBehindTokens; entry++ ) 
					interaction[entry] = new String(strTok.nextToken());
				
				variables.add(interaction);
			}
		} catch (IOException e ) {
			e.printStackTrace();
			System.exit(1);
		}
		
		return variables;
	}
}
